package bstsetcode.stanforduniversity18;

/**
 * @author noob
 * @version 1.0
 * @date 2021/3/15 16:53
 * 需求：获得链表第n个节点的值;
 * Write a GetNth() function that takes a linked list and an integer index and returns the data
 * value stored in the node at that index position. GetNth() uses the C numbering convention
 * that the first node is index 0, the second is index 1, ... and so on. So for the list {42, 13,
 * 666} GetNth() with index 1 should return 13. The index should be in the range [0..length-
 * 1]. If it is not, GetNth() should assert() fail (or you could implement some other error
 * case strategy)
 *
 */
public class _02_GetNth {



    public int getNth(ListNode head, int index) {

        ListNode cur = head;
        int i=0;
        while (i<index){
            cur = cur.next;
            i++;
        }
        return cur.val;
    }


    public static void main(String[] args) {

        int[] nums1 = {1,2,6,3,4,5,6,2,3,4,5,6};
        int[] nums2 = {0,1,2,3,4,5,6,7,8,9,10};
        ListNode head = new ListNode(nums2);
        int res = new _02_GetNth().getNth(head,2);
        System.out.println(res);
        /**
         * 当index=2;
         * 循环走2次，走到索引为1的位置；
         * cur.val就是我们要找的值
         */
    }
}
